<script setup>
import {computed, onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import http from '@/request/http.js'

// 存储当前用户等级信息
const currentLevelInfo = ref({})
// 存储所有等级数据
const allLevels = ref([])

// 获取当前等级ID（用于表格高亮）
const currentLevelId = computed(() => {
  return currentLevelInfo.value.currentLevel?.levelId || 1
})

// 判断是否为最高等级
const isMaxLevel = computed(() => {
  return !currentLevelInfo.value.nextLevel
})

// 等级对应颜色
const levelColor = computed(() => {
  const colors = [
    '#67c23a', // Lv1
    '#409eff', // Lv2
    '#e6a23c', // Lv3
    '#f56c6c', // Lv4
    '#909399'  // Lv5
  ]
  const level = currentLevelInfo.value.currentLevel?.levelId || 1
  return colors[level - 1] || colors[0]
})

const parsePrivileges = (privilegesStr) => {

  const str = privilegesStr?.toString() || '';
  if (!str.trim()) {
    return [];
  }

  //  解析JSON
  try {
    const parsed = JSON.parse(str);
    //  确保解析结果包含privileges数组
    return Array.isArray(parsed?.privileges) ? parsed.privileges : [];
  } catch (e) {
    console.error('权限解析失败:', e, '原始数据:', str);
    return [];
  }
};
// 获取等级数据
const loadLevelData = async () => {
  try {
    const [infoRes, levelsRes] = await Promise.all([
      http.get('/points/level/info'),
      http.get('/points/level/privileges')
    ]);

    currentLevelInfo.value = infoRes.data?.data || infoRes.data || {}
    allLevels.value = levelsRes.data?.data || levelsRes.data || []
  } catch (error) {
    console.error('加载等级数据失败:', error);
    ElMessage.error('加载等级信息失败，请刷新重试');
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadLevelData()
})
</script>
<template>
  <div class="level-page">
    <!-- 等级信息卡片 -->
    <el-card class="level-card" shadow="hover">
      <div class="level-header">
        <h2>我的等级</h2>
        <div class="level-display">
          <span class="level-number">{{ currentLevelInfo.currentLevel?.levelId || 1 }}</span>
          <span class="level-name">{{ currentLevelInfo.currentLevel?.levelName || 'Lv.1 新手' }}</span>
        </div>
      </div>

      <!-- 升级进度条 -->
      <div class="progress-container">
        <div class="progress-stats">
          <span>当前积分：{{ currentLevelInfo.totalPoints || 0 }}</span>
          <span v-if="!isMaxLevel">
            距离升级还需：{{ Math.max(0, currentLevelInfo.nextLevel.minPoints - currentLevelInfo.totalPoints) }} 积分
          </span>
          <span v-else>已达最高等级</span>
        </div>

        <el-progress
            :percentage="Number(currentLevelInfo.progress || 0)"
            :stroke-width="8"
            :color="levelColor"
            :status="isMaxLevel ? 'success' : ''"
        ></el-progress>

        <div v-if="!isMaxLevel" class="level-transition">
          <span>{{ currentLevelInfo.currentLevel.levelName }}</span>
          <i class="el-icon-arrow-right"></i>
          <span>{{ currentLevelInfo.nextLevel.levelName }}</span>
        </div>
      </div>
    </el-card>

    <!-- 等级权限表 -->
    <el-card class="privileges-card" shadow="hover">
      <h2>等级权限说明</h2>
      <el-table
          :data="allLevels"
          border
          :current-row-key="currentLevelId"
          highlight-current-row
          style="width: 100%; margin-top: 15px"
      >
        <el-table-column
            prop="levelId"
            label="等级ID"
            width="80"
        ></el-table-column>
        <el-table-column
            prop="levelName"
            label="等级名称"
            width="140"
        ></el-table-column>
        <el-table-column
            prop="minPoints"
            label="所需最低积分"
            width="120"
        ></el-table-column>
        <el-table-column
            label="权限列表"
        >
          <template #default="scope">
            <div v-for="(priv, idx) in parsePrivileges(scope.row.privileges)" :key="idx" class="privilege-item">
              <i class="el-icon-check text-success"></i>
              <span>{{ priv }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<style scoped>
.level-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.level-card {
  margin-bottom: 20px;
  padding: 20px;
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.level-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.level-number {
  font-size: 36px;
  font-weight: bold;
  color: #409eff;
}

.level-name {
  font-size: 20px;
  color: #333;
}

.progress-container {
  margin-top: 15px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.level-transition {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
  color: #666;
}

.privileges-card {
  padding: 20px;
}

.privilege-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 14px;
}

.text-success {
  color: #67c23a;
}

.el-table .current-row {
  background-color: #f0f7ff !important;
}
</style>
